package com.xlhj.yucloud.filter;

import com.xlhj.yucloud.web.service.TokenService;
import com.xlhj.yucloud.web.service.UserDetailsServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: liucaijing
 * @description: JwtAuthTokenFilter
 * @date: 2021/9/10 9:39
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求中解析token
        String token = tokenService.getToken(request);
        if (!StringUtils.hasLength(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        //从令牌中解析声明
        Claims claims = tokenService.getClaimsFromToken(token);
        if (null == claims) {
            throw new RuntimeException("token exception");
        }
        //判断token是否过期
        Boolean tokenExpired = tokenService.isTokenExpired(claims);
        if (tokenExpired) {
            throw new RuntimeException("The token has expired");
        }
        String userId = claims.get("id").toString();
        String username = claims.getSubject();
        //查询权限
        List<SimpleGrantedAuthority> authorities = userDetailsService.getUserAuthorities(Long.valueOf(userId));
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);
    }
}
